package cn.sfa.controller.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.taglib.CommonCache;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.role.SaleModule;
import cn.sfa.entity.role.SaleRole;
import cn.sfa.entity.role.SaleUserRole;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.role.RoleService;

/**
 * 角色管理控制器类
 * 
 * @ClassName：ManageRoleController
 * @Description：TODO
 * @author：LiXiang
 * @date：2012-7-4 上午9:57:00
 * 
 */
@Controller
@RequestMapping("manage/role/index")
public class ManageRoleController extends WebInitBinderContoller {

	Logger log = LoggerFactory.getLogger(ManageRoleController.class);
	@Autowired
	RoleService roleService;
	
	@Autowired
	LoginService loginService;

	private Pagination pagination;// 分页

	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}
	
		
	/**
	 * 显示所有角色
	 * TODO
	 * @author: LiXiang
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/getroles")
	public String getRoles(
			HttpServletRequest request,
			@RequestParam(value = "currentPage", required = false) String currentPage,
			@RequestParam(value = "roleName", required = false) String roleName,
			ModelMap map
			) {

		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}

		Pagination pagination = null;
		pagination = roleService.getRole(
				roleName,
				pageIndex,
				10,
				request.getContextPath()
						+ "/manage/role/index/getroles?"
						+ "&roleName="+roleName);

		map.put("pagination", pagination);
		map.put("roleName", roleName);
		map.put("page", pageIndex);

		return "/manage/role/getroles";
	}
	
	/**
	 * 修改角色信息
	 * TODO
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param checkModes
	 * @param roleName
	 * @param roleContent
	 * @param isBaseRole
	 * @param map
	 */
	@RequestMapping(value = "/editrole")
	public void editRoleDetail(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "checkModes", required = false) String checkModes,
			@RequestParam(value = "roleName", required = false) String roleName,
			@RequestParam(value = "roleContent", required = false) String roleContent,
			@RequestParam(value = "isBaseRole", required = false) String isBaseRole,
			@RequestParam(value = "roleStatus", required = false) String roleStatus,
			ModelMap map) {
		
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		
		String[] args = checkModes.split(",");
		SaleRole saleRole = roleService.getRoleById(id);
		saleRole.setRoleName(roleName);
		saleRole.setRoleContent(roleContent);
		saleRole.setRoleStatus(roleStatus);
		boolean successAddRole = roleService.updateRole(saleRole); //step1:修改角色信息
		successAddRole = roleService.deleteRoleModuleById(saleRole.getSaleRoleId()); //step2:删除当前角色对应所有模块
		if(successAddRole){
			for(int i=0;i<args.length;i++){
				if(!"".equals(args[i])&&!"0".equals(args[i])&&null!=args[i]){
					roleService.addRoleModule(saleRole.getSaleRoleId(),args[i],new Date(),user.getSaleUsersLoginId());
				}
			}
			CommonCache.setCacheFunctionlModelNull();
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		response.setContentType("text/json");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(jsonObject);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 新增角色
	 * TODO
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param checkModes
	 * @param roleName
	 * @param roleContent
	 * @param isBaseRole
	 * @param map
	 */
	@RequestMapping(value = "/newrole")
	public void newRole(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "checkModes", required = false) String checkModes,
			@RequestParam(value = "roleName", required = false) String roleName,
			@RequestParam(value = "roleContent", required = false) String roleContent,
			@RequestParam(value = "isBaseRole", required = false) String isBaseRole,
			@RequestParam(value = "roleStatus", required = false) String roleStatus,
			ModelMap map) {
		
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		
		String[] args = checkModes.split(",");
		SaleRole saleRole = new SaleRole();
		saleRole.setCreateDate(new Date());
		saleRole.setCreateUid(user.getSaleUsersLoginId());
		saleRole.setIsBaseRole("0");
		saleRole.setRoleName(roleName);
		saleRole.setRoleContent(roleContent);
		saleRole.setRoleStatus(roleStatus);
		String successAddRole = roleService.addRole(saleRole);
		if(successAddRole!=null){
			for(int i=0;i<args.length;i++){
				if(!"".equals(args[i])&&!"0".equals(args[i])&&null!=args[i]){
					roleService.addRoleModule(successAddRole,args[i],new Date(),user.getSaleUsersLoginId());
				}
			}
			CommonCache.setCacheFunctionlModelNull();
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		response.setContentType("text/json");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(jsonObject);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 验证角色
	 * TODO
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param checkModes
	 * @param roleName
	 * @param roleContent
	 * @param isBaseRole
	 * @param map
	 */
	@RequestMapping(value = "/validate")
	public void validate(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "roleName", required = false) String roleName,
			ModelMap map) {
		
		JSONObject jsonObject = new JSONObject();
		boolean result = true;
		if (CommonUtil.isEmpty(roleName.trim())) {
			roleName = "角色名不能为空！";
			result = false;
		} else if (roleName.length() < 2 || roleName.length() > 15) {
			roleName = "角色名长度必须在2到15位";
			result = false;
		}
		jsonObject.put("result", result);
		jsonObject.put("roleName", roleName);
		response.setContentType("text/json");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(jsonObject);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 进入新增页面 TODO
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param map
	 * @param list
	 * @return
	 */
	@RequestMapping(value = "/getmodule")
	public String index(HttpServletRequest request, ModelMap map) {
		return "/manage/role/newrole";
	}
	
	/**
	 * 进入修改页面
	 * TODO
	 * @author: LiXiang
	 * @param request
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/getmoduleforedit")
	public String edit(HttpServletRequest request, 
			@RequestParam(value = "id", required = false) String id,
			ModelMap map) {
		SaleRole saleRole = roleService.getRoleById(id);
		
		List list = roleService.getRoleMoudleById(id);
		String moduleIds = "";
		for(int i=0;i<list.size();i++){
			moduleIds += ","+((Map)list.get(i)).get("moduleid");
		}
		map.put("id", id);
		map.put("roleName", saleRole.getRoleName());
		map.put("moduleIds", moduleIds);
		map.put("roleContent", saleRole.getRoleContent());
		map.put("roleStatus", saleRole.getRoleStatus());
		return "/manage/role/editrole";
	}
	
	/**
	 * delete
	 * TODO
	 * @author: LiXiang
	 * @param response
	 * @param saleRoleId
	 * @throws IOException
	 */
	@RequestMapping("/delete/{saleRoleId}")
	public void delete(HttpServletResponse response, @PathVariable("saleRoleId") String saleRoleId) throws IOException {
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		boolean flag = roleService.deleteRoleById(saleRoleId);
		if(flag) CommonCache.setCacheFunctionlModelNull();
		JSONObject jo = new JSONObject();
		jo.put("isDel", flag);
		out.print(jo);
		out.flush();
		out.close();
	}
	
	/**
	 * ajax显示所有模块
	 * TODO
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 */
	@RequestMapping(value = "/ajaxgetmodule")
	public void getModule(HttpServletRequest request,HttpServletResponse response, ModelMap map) {
		List<SaleModule> list = roleService.getModule("0");
		List children = new ArrayList();
		for (SaleModule object : list) {
			JSONObject jsonObject = searialTcatgory(object);
			children.add(jsonObject);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("text", "所有");
		jsonObject.put("checked", "0");
		jsonObject.put("pid", "0");
		jsonObject.put("id", "0");
		jsonObject.put("children", children);
		jsonObject.toString();
		try {
			response.setContentType("text/json");
			PrintWriter out = response.getWriter();
			out.print(jsonObject);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private JSONObject searialTcatgory(SaleModule saleRole) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("text", saleRole.getModuleName());
		jsonObject.put("pid", saleRole.getParentModuleId());
		jsonObject.put("id", saleRole.getModuleId());
		jsonObject.put("checked", "0");
		List list = searialChild(saleRole);
		jsonObject.put("children", list);
		return jsonObject;
	}

	private List searialChild(SaleModule saleRole) {
		List children = null;
		List<SaleModule> list = getByParentId(saleRole.getModuleId());
		if (list != null && list.size() > 0) {
			children = new ArrayList();
		}
		for (SaleModule object : list) {
			JSONObject jsonObject = searialTcatgory(object);
			children.add(jsonObject);
		}
		return children;
	}

	private List getByParentId(String id) {
		return roleService.getModule(id);
	}
	
	
	
	@RequestMapping(value = "/getAllUsers")
	public String getAllUsers(HttpServletRequest request, ModelMap map,
			@RequestParam(value="currentPage", required=false) String currentPage,
			SaleUsersLogin saleUser,
			@RequestParam(value="beginCreateDate", required=false)String beginCreateDate,
			@RequestParam(value="endCreateDate", required=false)String endCreateDate) {
		int pageIndex;
		try{
			pageIndex = Integer.valueOf(currentPage);
		}catch(Exception ex){
			pageIndex = 1;
		} 
		Pagination pagination=loginService.getAllUsers(pageIndex, 10, request.getContextPath()+"/manage/role/index/getAllUsers?" +
				"loginName="+CommonUtil.jugeAndFixNull(saleUser.getLoginName())+
				"&userName="+CommonUtil.jugeAndFixNull(saleUser.getUserName())+
				"&userType="+CommonUtil.jugeAndFixNull(saleUser.getUserType())+
				"&beginCreateDate="+(CommonUtil.isEmpty(beginCreateDate) ? "" :  beginCreateDate)+
				"&endCreateDate="+(CommonUtil.isEmpty(endCreateDate) ? "" :  endCreateDate),saleUser,beginCreateDate,endCreateDate);
		
		map.put("pagination", pagination);
		map.put("loginName",saleUser.getLoginName());
		map.put("userName",saleUser.getUserName());
		map.put("userType",saleUser.getUserType());
		map.put("beginCreateDate", CommonUtil.isEmpty(beginCreateDate) ? ""
				:  beginCreateDate);
		map.put("endCreateDate", CommonUtil.isEmpty(endCreateDate) ? ""
				:  endCreateDate);
		map.put("page",pageIndex); 
		return "/manage/userrole/users";
	}
	
	@RequestMapping(value = "/toUserRole")
	public String toUserRole(HttpServletRequest request, ModelMap map,
			@RequestParam(value="currentPage", required=false) String currentPage,
			 
			@RequestParam(value="saleUsersLoginId", required=false)String saleUsersLoginId) {
		
		
		//查询所有角色
		List list=roleService.getRoles();
		//查询用户已有的角色
		List elist=roleService.getRoles(saleUsersLoginId);
		String[] myrole=new String[elist.size()];
		
		System.out.println("=========================saleUsersLoginId:::"+elist.size());
		for(int i=0;i<elist.size();i++)
		{
			Map<String,Object> object=(Map<String,Object>)elist.get(i);
			String role=(String)object.get("roleid");
			System.out.println("=========================saleUsersLoginId:::"+role);
			myrole[i]=role;
		}
		
		List<String> ids=new ArrayList<String>(Arrays.asList(myrole));
		
		map.put("myrole", ids);
		//查询用户信息
		SaleUsersLogin user=loginService.getUserById(saleUsersLoginId);
		
		map.put("user", user);
		map.put("roles", list);
		
		return "/manage/userrole/userrole";
	}
	
	
	/**
	 * 编辑角色
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping(value=("/manageUserRole"))
	public void update(SaleUserRole saleUserRole,HttpServletRequest request,ModelMap map,
			HttpServletResponse response) throws Exception
	{
		//表单验证
		 
		String[] temps=null;
		saleUserRole.setRoleId(saleUserRole.getRoleId()[0].split(","));
		int count=0;
		String json="";
		String msg="";
		String path = request.getContextPath();
		  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		 if(saleUserRole.getRoleId()[0]=="")
		{
			msg="请选择要给用户绑定的角色！";
			count=count+1;
		}
		 
		boolean result=count==0;
		

		PrintWriter out = response.getWriter();

		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");

		
		
		if(result)
		{
			saleUserRole.setCreateDate(new Date());
			saleUserRole.setUpdateDate(new Date());
			saleUserRole.setCreateUid(user.getSaleUsersLoginId());
			saleUserRole.setUpdateId(user.getSaleUsersLoginId());
			
			boolean flag=roleService.updateRoles(saleUserRole);
			
			if(flag)
			{ 
					msg="绑定用户角色成功！";
			 
			}else 
			{
				msg="绑定用户角色失败！";
			}
			
		}
		
		  
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
         
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("msg", msg);
	        out.print(temp.toString());
			out.flush();
			out.close();
	}
	
}
